1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| #include <bits/stdc++.h> #define rep(i, x, y) for (int i = x; i <= y; i++) using namespace std;
typedef long long ll; typedef pair<ll, ll> pll; const int N = 1e5 + 10; const ll inf = 1e18; ll n, m, X[N], Y[N], W[N], C[N]; ll ans, tot; priority_queue<pll, vector<pll>, greater<pll> > A, B;
void push_x(ll x) { ll y; if (B.empty()) y = inf; else y = B.top().first; ans += x + y; A.push(make_pair(-2 * x - y, 1)); if (B.size()) { ll t = B.top().second; B.pop(); if (t > 1) B.push(make_pair(y, t - 1)); } }
void push_y(ll y, ll w, ll c) { ll m = 0; while (c != m && A.size() && y + w + A.top().first < 0) { ll x = A.top().first; ll t = A.top().second, tt = min(c - m, t); ans += tt * (x + y + w); A.pop(); if (tt != t) A.push(make_pair(x, t - tt)); B.push(make_pair(-x - 2 * y, tt)); m += tt; } if (m) A.push(make_pair(-y - w, m)); if (c != m) B.push(make_pair(-y + w, c - m)); }
int main() { cin >> n >> m; rep(i, 1, n) scanf("%lld", &X[i]); rep(i, 1, m) scanf("%lld%lld%lld", &Y[i], &W[i], &C[i]), tot += C[i]; if (tot < n) return puts("-1"), 0; int i = 1, j = 1; while (i <= n && j <= m) { if (X[i] < Y[j]) push_x(X[i]), ++i; else push_y(Y[j], W[j], C[j]), ++j; } while (i <= n) push_x(X[i]), ++i; while (j <= m) push_y(Y[j], W[j], C[j]), ++j; printf("%lld\n", ans); return 0; }
|